package com.gushuang.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
//https://leetcode.cn/problems/merge-intervals
public class mergeIntervals {
    public static int[][] merge(int[][] intervals) {
       if(intervals.length==0){
           return new int[0][];
       }
        Arrays.sort(intervals, Comparator.comparingInt(a->a[0]));
        ArrayList<int[]> merged = new ArrayList<>();
        int [] currentInterval= intervals[0];
        merged.add(currentInterval);
        for (int[] interval : intervals) {
            int currentEnd= currentInterval[1];
            int nextStart=interval[0];
            int nextEnd=interval[1];
            if(currentEnd>=nextStart){// 1 3         2 6
                currentInterval[1]=Math.max(currentEnd,nextEnd);
            }else{
                currentInterval = interval;
                merged.add(currentInterval);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }
    public static void main(String[] args) {
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] mergedIntervals = merge(intervals);

        System.out.println("合并后的区间：");
        for (int[] interval : mergedIntervals) {
            System.out.println("[" + interval[0] + ", " + interval[1] + "]");
        }
    }
}
